<template>
  <div class="favorites-page">
    <div class="container">
      <el-card class="favorites-card">
        <template #header>
          <h2>我的收藏</h2>
        </template>

        <div class="favorites-content">
          <template v-if="carStore.loading">
            <div class="loading-container">
              <el-skeleton :rows="6" animated />
            </div>
          </template>

          <template v-else>
            <div v-if="carStore.favorites.length === 0" class="empty-state">
              <el-empty description="暂无收藏车辆">
                <el-button type="primary" @click="navigateTo('/cars')">
                  去逛逛
                </el-button>
              </el-empty>
            </div>

            <div v-else class="favorites-list">
              <el-card
                v-for="car in carStore.favorites"
                :key="car.id"
                class="favorite-item"
                shadow="hover"
              >
                <div class="car-image" @click="navigateTo(`/car/${car.id}`)">
                  <img :src="car.images?.[0] || '/images/default-car.png'" :alt="car.title">
                  <div class="car-tags">
                    <el-tag v-if="car.isNew" type="success" size="small">准新车</el-tag>
                    <el-tag v-if="car.hot" type="danger" size="small">热门</el-tag>
                  </div>
                </div>

                <div class="car-info">
                  <h3 class="car-title" @click="navigateTo(`/car/${car.id}`)">
                    {{ car.title }}
                  </h3>
                  <p class="car-desc">{{ car.desc }}</p>

                  <div class="car-meta">
                    <div class="meta-item">
                      <el-icon><Odometer /></el-icon>
                      <span>{{ car.distance }}万公里</span>
                    </div>
                    <div class="meta-item">
                      <el-icon><Calendar /></el-icon>
                      <span>{{ car.regDate }}上牌</span>
                    </div>
                    <div class="meta-item">
                      <el-icon><Location /></el-icon>
                      <span>{{ car.location }}</span>
                    </div>
                  </div>

                  <div class="car-price">
                    <span class="price">{{ car.price }}万</span>
                    <span class="original-price" v-if="car.originalPrice">
                      新车{{ car.originalPrice }}万
                    </span>
                  </div>
                </div>

                <div class="car-actions">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="handleContact(car)"
                  >
                    联系卖家
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small"
                    :icon="Delete"
                    @click="removeFavoriteItem(car.id)"
                  >
                    取消收藏
                  </el-button>
                </div>
              </el-card>
            </div>

            <!-- 批量操作 -->
            <div class="batch-actions" v-if="carStore.favorites.length > 0">
              <el-button 
                type="danger" 
                :icon="Delete"
                @click="handleBatchRemove"
                :disabled="selectedCars.length === 0"
              >
                批量删除 ({{ selectedCars.length }})
              </el-button>
              <el-checkbox
                v-model="selectAll"
                @change="handleSelectAll"
              >
                全选
              </el-checkbox>
            </div>
          </template>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Delete, Odometer, Calendar, Location } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCarStore } from '@/store/car'

const router = useRouter()
const carStore = useCarStore()

const selectedCars = ref([])
const selectAll = ref(false)
const isComponentMounted = ref(true)

// 添加路由导航方法
const navigateTo = (path) => {
  router.push(path)
}

const handleContact = (car) => {
  ElMessage.success(`联系卖家: ${car.seller?.phone || '400-123-4567'}`)
}

const removeFavoriteItem = async (carId) => {
  if (!isComponentMounted.value) return
  
  try {
    await ElMessageBox.confirm('确定要取消收藏吗？', '提示', {
      type: 'warning'
    })
    
    await carStore.removeFavorite(carId)
    ElMessage.success('取消收藏成功')
    
    // 从选中列表中移除
    const index = selectedCars.value.indexOf(carId)
    if (index > -1) {
      selectedCars.value.splice(index, 1)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消收藏失败')
    }
  }
}

const handleBatchRemove = async () => {
  if (!isComponentMounted.value) return
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedCars.value.length} 个收藏吗？`, '提示', {
      type: 'warning'
    })
    
    for (const carId of selectedCars.value) {
      await carStore.removeFavorite(carId)
    }
    
    ElMessage.success('批量删除成功')
    selectedCars.value = []
    selectAll.value = false
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const handleSelectAll = (checked) => {
  if (!isComponentMounted.value) return
  
  if (checked) {
    selectedCars.value = carStore.favorites.map(car => car.id)
  } else {
    selectedCars.value = []
  }
}

// 监听收藏列表变化
const favoritesCount = computed(() => carStore.favorites.length)

onMounted(async () => {
  isComponentMounted.value = true
  try {
    await carStore.fetchFavorites()
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    ElMessage.error('加载收藏列表失败')
  }
})

onUnmounted(() => {
  isComponentMounted.value = false
})
</script>

<style lang="scss" scoped>
.favorites-page {
  padding: 20px 0;

  .container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 20px;
  }
}

.favorites-card {
  :deep(.el-card__header) {
    border-bottom: 1px solid #f0f0f0;
    padding: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      color: #333;
    }
  }
}

.favorites-content {
  padding: 20px;
}

.loading-container {
  padding: 40px 0;
}

.empty-state {
  padding: 60px 0;
}

.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.favorite-item {
  display: flex;
  gap: 20px;
  padding: 20px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .car-image {
    width: 200px;
    height: 150px;
    flex-shrink: 0;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    position: relative;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s;
    }

    &:hover img {
      transform: scale(1.05);
    }

    .car-tags {
      position: absolute;
      top: 10px;
      left: 10px;
      display: flex;
      gap: 5px;
    }
  }

  .car-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .car-title {
      margin: 0 0 8px;
      font-size: 18px;
      color: #333;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #ff6a00;
      }
    }

    .car-desc {
      margin: 0 0 12px;
      color: #666;
      font-size: 14px;
      line-height: 1.5;
    }

    .car-meta {
      display: flex;
      gap: 20px;
      margin-bottom: 12px;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        color: #999;

        .el-icon {
          font-size: 14px;
        }
      }
    }

    .car-price {
      display: flex;
      align-items: center;
      gap: 12px;

      .price {
        font-size: 20px;
        font-weight: bold;
        color: #ff6a00;
      }

      .original-price {
        font-size: 12px;
        color: #999;
        text-decoration: line-through;
      }
    }
  }

  .car-actions {
    display: flex;
    flex-direction: column;
    gap: 8px;
    justify-content: center;
  }
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .favorite-item {
    flex-direction: column;
    gap: 15px;

    .car-image {
      width: 100%;
      height: 200px;
    }

    .car-actions {
      flex-direction: row;
      justify-content: flex-start;
    }
  }

  .batch-actions {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
}
</style>